const database = require("../../database/index");
const dayjs = require("dayjs");

// 添加分类
exports.add = (req, res) => {
    const sql = 'select * from category where name=?';
    const sql1 = "insert into category set ?";
    const created = dayjs().format("YYYY-MM-DD HH:mm:ss");
    database.query(sql, [req.body.name], function (err, results) {
        if (err) {
            return res.response(err);
        };
        if (results.length > 0) {
            return res.response("分类已存在");
        };
        database.query(
            sql1,
            {
                ...req.body,
                created,
            },
            function (err) {
                if (err) return res.response(err);
                res.response("添加成功", 0);
            }
        );
    });
};

// 删除分类
exports.delete = (req, res) => {
    const { id } = req.body;
    const sql = "delete from category where id=?";
    database.query(sql, id, (err) => {
        if (err) return res.response(err);
        res.response("删除成功", 0);
    });
};

// 修改分类
exports.edit = (req, res) => {
    const { id } = req.body;
    const sql = 'select * from category where name=?';
    database.query(sql, [req.body.name], function (err, results) {
        if (err) {
            return res.response(err);
        };
        if (results.length > 0 && results[0].id != id) {
            return res.response("分类已存在");
        };
        let sql = "update category set ? where id=?";
        const updated = dayjs().format("YYYY-MM-DD HH:mm:ss");
        database.query(sql, [{ ...req.body, updated }, id], (err) => {
            if (err) return res.response(err);
            res.response("修改成功", 0);
        });
    });
};

// 查询分类
exports.list = (req, res) => {
    const { content, page, pageSize } = req.body;
    let sql = "select * from category";
    let countSql = "select count(*) as total from category";
    let params = [];
    if (content) {
        sql += sql.includes("where") ? " and (name like?)" : " where (name like?)";
        countSql += countSql.includes("where") ? " and (name like?)" : " where (name like?)";
        params.push(`%${content}%`)
    };
    database.query(countSql, params, function (countErr, countResult) {
        if (countErr) return res.response(countErr);
        const total = countResult[0] ? countResult[0].total : 0;
        if (page && pageSize) {
            const offset = (page - 1) * pageSize;
            sql += " LIMIT ? OFFSET ?";
            params.push(Number(pageSize), offset);
        }
        database.query(sql, params, function (err, result) {
            if (err) return res.response(err);
            return res.send({
                code: 0,
                message: "查询成功",
                total,
                result,
            });
        });
    });
};

